//
//  XYTVerifyCodeView.m
//  XYTPayOrderSystem
//
//  Created by wupeng on 2017/8/28.
//  Copyright © 2017年 wupeng. All rights reserved.
//

#import "XYTVerifyCodeView.h"

@interface XYTVerifyCodeView ()
{
    dispatch_source_t _timer;
}

@property (readwrite) NSInteger countdown;

@end

@implementation XYTVerifyCodeView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    self.backgroundColor = [UIColor colorWithRed:220.0f/255.0 green:164.0f/255.0 blue:74.0f/255.0f alpha:1];
    [self.layer setCornerRadius:2.0];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.titleLabel.font = [UIFont systemFontOfSize:14];
    self.timeLimit = 60; //默认60s
    
    [self updateBtnCodeTitleStatus];
}

- (void)updateBtnCodeTitleStatus
{
    if (self.selected) {
        NSString *title = [NSString stringWithFormat:@"%ld秒后重新发送", (long)_countdown];
        [self setTitle:title forState:UIControlStateNormal];
        self.userInteractionEnabled = NO;
    }else{
        [self setTitle:@"发送验证码" forState:UIControlStateNormal];
        self.userInteractionEnabled = YES;
    }
}

- (void)startCountdown
{
    self.selected = YES;
    
    [self updateBtnCodeTitleStatus];
    
    [self updateCountdownTime];
}

- (void)updateCountdownTime
{
    _countdown = _timeLimit;
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        _countdown --;
        [self updateBtnCodeTitleStatus];
        if (_countdown <= 0) {
            [self clearBtnCountdownStatus];
        }
    });
    dispatch_resume(_timer);
}

- (void)removeTimer
{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}

- (void)clearBtnCountdownStatus
{
    [self removeTimer];
    
    self.selected = NO;
    
    [self updateBtnCodeTitleStatus];
}

- (void)setTimeLimit:(NSInteger)timeLimit
{
    _timeLimit = timeLimit;
    
    _countdown = timeLimit;
}

- (void)dealloc
{
    [self removeTimer];
    _timer = nil;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
